import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { RootState } from "./store";

// state的类型
interface AppState {
  lang: string;
}

// 计算产生初始状态的函数
function getInitialState(): AppState {
  const lang = localStorage.getItem("lang") || "zh_CN";

  return {
    lang,
  };
}

// 初始状态
let initialState: AppState = getInitialState();

// 当前redux模块的管理对象slice
export const appSlice = createSlice({
  name: "app", // 标识名称
  initialState, // 初始化状态数据
  // 定义reducer函数 --> 会自动生成同步action函数
  reducers: {
    // 设置语言的reducer处理
    setLang(state, action: PayloadAction<string>) {
      const lang = action.payload;
      // 更新状态
      state.lang = lang;
      // 保存到local
      localStorage.setItem("lang", lang);
    },
  },
});

// reducer函数
export const appReducer = appSlice.reducer;

// action creator函数
export const { setLang } = appSlice.actions;

// 读取模块状态数据的select函数
export const selectLang = (state: RootState) => state.app.lang;

